package com.chj.design.sk;

//https://www.cnblogs.com/java-my-life/archive/2012/06/01/2526972.html
public class Code04_Command2 {

	// 录音机类扮演
	public static class AudioPlayer {

		public void play() {
			System.out.println("播放...");
		}

		public void rewind() {
			System.out.println("倒带...");
		}

		public void stop() {
			System.out.println("停止...");
		}
	}

	// 抽象命令角色类
	public interface Command {
		/**
		 * 执行方法
		 */
		public void execute();
	}

	// 具体命令角色类
	public static class PlayCommand implements Command {

		private AudioPlayer myAudio;

		public PlayCommand(AudioPlayer audioPlayer) {
			myAudio = audioPlayer;
		}

		/**
		 * 执行方法
		 */
		@Override
		public void execute() {
			myAudio.play();
		}

	}

	public static class RewindCommand implements Command {

		private AudioPlayer myAudio;

		public RewindCommand(AudioPlayer audioPlayer) {
			myAudio = audioPlayer;
		}

		@Override
		public void execute() {
			myAudio.rewind();
		}

	}

	public static class StopCommand implements Command {
		private AudioPlayer myAudio;

		public StopCommand(AudioPlayer audioPlayer) {
			myAudio = audioPlayer;
		}

		@Override
		public void execute() {
			myAudio.stop();
		}
	}

	// 请求者角色 由键盘类扮演
	public static class Keypad {
		private Command playCommand;
		private Command rewindCommand;
		private Command stopCommand;

		public void setPlayCommand(Command playCommand) {
			this.playCommand = playCommand;
		}

		public void setRewindCommand(Command rewindCommand) {
			this.rewindCommand = rewindCommand;
		}

		public void setStopCommand(Command stopCommand) {
			this.stopCommand = stopCommand;
		}

		/**
		 * 执行播放方法
		 */
		public void play() {
			playCommand.execute();
		}

		/**
		 * 执行倒带方法
		 */
		public void rewind() {
			rewindCommand.execute();
		}

		/**
		 * 执行播放方法
		 */
		public void stop() {
			stopCommand.execute();
		}
	}

	public static void main(String[] args) {
		// 创建接收者对象
		AudioPlayer audioPlayer = new AudioPlayer();
		// 创建命令对象
		Command playCommand = new PlayCommand(audioPlayer);
		Command rewindCommand = new RewindCommand(audioPlayer);
		Command stopCommand = new StopCommand(audioPlayer);
		// 创建请求者对象
		Keypad keypad = new Keypad();
		keypad.setPlayCommand(playCommand);
		keypad.setRewindCommand(rewindCommand);
		keypad.setStopCommand(stopCommand);
		// 测试
		keypad.play();
		keypad.rewind();
		keypad.stop();
		keypad.play();
		keypad.stop();
	}
}
